package com.example.josan.rxbus;

import android.support.annotation.NonNull;

import io.reactivex.Observable;
import io.reactivex.functions.Predicate;
import io.reactivex.subjects.PublishSubject;
import io.reactivex.subjects.Subject;

/**
 * Created by wochacha on 2017/12/5.
 * 使用rxjava实现Event bus功能
 */

public class RxBus {
    private final Subject<Object> mBus;

    private RxBus() {
        mBus = PublishSubject.create().toSerialized();
    }

    public static RxBus getInstance() {
        return Holder.BUS;
    }

    private static class Holder {
        private static final RxBus BUS = new RxBus();
    }

    public Observable<Object> register() {
        return mBus;
    }

    public Observable<? extends RxBusBean> register(Class<? extends RxBusBean> tClass) {
        return mBus.ofType(tClass);
    }

    public Observable<? extends RxBusBean> register(Class<? extends RxBusBean> tClass, final int tag) {
        return mBus.ofType(tClass).filter(new Predicate<RxBusBean>() {
            @Override
            public boolean test(RxBusBean t) throws Exception {
                return t.tag == tag;
            }
        });
    }

    public void postEmpty(int tag){
        EmptyBean emptyBean = new EmptyBean();
        post(tag, emptyBean);
    }

    public void postString(int tag, String content) {
        StringBean emptyBean = new StringBean(content);
        post(tag, emptyBean);
    }

    public void post(@NonNull RxBusBean rxBusBean) {
        post(0, rxBusBean);
    }
    public void post(int tag, @NonNull RxBusBean rxBusBean) {
        if (tag != 0) {
            rxBusBean.tag = tag;
        }
        mBus.onNext(rxBusBean);
    }

    public boolean hasObservers() {
        return mBus.hasObservers();
    }

    public void unregisterAll() {
        // 会将所有由mBus生成的Observable都置为completed状态，后续都消息都收不到了
        mBus.onComplete();
    }

}
